<template>
  <div class="min-wrap">
    <div class="min-head">
      <a class="text-btn"
        @click="changeDialogType('phoneLogin')">已有账号？<span>立即登录</span></a>
    </div>

    <div class="body-wrap">
      <header class="head">
        注册
      </header>
      <PhoneForm v-model="form"
        ref="form"
        pwdPlaceholder="密码为8-16位，必须包含数字和字母"
        :layout="['phone', 'code','pwd','pwd2']"
        :errMsgOffset="169"
        @handleEnter="submitRegister"/>

      <el-form>
        <el-form-item style="margin-top:34px">
          <el-button class="login-btn"
            :loading="loading"
            type="primary"
            @click="submitRegister">注册</el-button>
        </el-form-item>

        <el-form-item>
          <div class="checkbox-wrap">
            <el-checkbox v-model="form.isAutoLogin">15天内自动登录</el-checkbox>
            <el-checkbox v-model="form.isRead">
              <div class="checkbox-btn">已阅读并同意<a @click.prevent="openUrl">用户协议</a></div>
            </el-checkbox>
          </div>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { debounce, getPwdMD5Str } from '@/utils'
import { register, checkUserIsExist } from '@/api/login'
import PhoneForm from '@/components/phone-form/index.vue'
import mixins from './mixins'
export default {
  name: 'Register',
  mixins: [mixins],
  components: {
    PhoneForm
  },
  props: {
    isPage: Boolean
  },
  data () {
    return {
      loading: false,
      form: {
        phoneNumber: undefined,
        code: undefined,
        pwd: undefined,
        pwd2: undefined,
        isAutoLogin: true,
        isRead: false
      }
    }
  },
  computed: {
    ...mapGetters(['appInfo', 'appCfg']),
    showValidateErrMsg () {
      return (this.$refs.form && this.$refs.form.showValidateErrMsg) || debounce((errMsg) => {
        this.$PsMessage({ message: errMsg, offset: 169 })
      }, 1000, true)
    }
  },
  created () {
    this.$xz('xz_SetTitleMenuRectEx', {
      x: 66,
      y: 14,
      nx: 48,
      ny: 16
    })
  },
  beforeDestroy () {
    this.$xz('xz_SetTitleMenuRectEx', {
      x: 0,
      y: 0,
      nx: 0,
      ny: 0
    })
  },
  methods: {
    openUrl () {
      this.$xz('xz_open_url', `${this.appCfg.site}/user-protocol.html`)
    },
    /**
     * 提交注册
     */
    submitRegister () {
      this.$refs.form.validate().then(() => {
        if (!this.form.isRead) {
          return this.showValidateErrMsg('请勾选用户协议')
        }
        this.$refs.form.phoneError = ''
        checkUserIsExist(this.form.phoneNumber, { offset: 169 }).then(res => {
          if (res.data.existed) {
            const msg = '该手机号已注册'
            this.showValidateErrMsg(msg)
            this.$refs.form.phoneError = msg
          } else {
            this.onRegister()
          }
        })
      })
    },
    onRegister () {
      const params = {
        phoneNumber: this.form.phoneNumber,
        codeID: this.form.codeID || this.form.phoneNumber,
        code: this.form.code,
        pwd: getPwdMD5Str(this.form.pwd),
        appid: process.env.VUE_APP_ID,
        'channel': this.appInfo.channel, // 渠道信息
        'uuid': this.appInfo.uuid, // 设备信息
        'device_name': this.appInfo.device_name, // 设备名称
        'version': this.appInfo.version // 版本号
      }
      this.$xz('xz_substat_action', 1733)
      this.$refs.form.phoneError = ''
      this.loading = true
      register(params, { offset: 169 }).then(res => {
        this.loading = false
        const data = res.data || {}
        this.$store.dispatch('user/setToken', data.code)
        this.$store.dispatch('user/getUserInfo').then(info => {
          this.onLoginFinish({
            isAutoLogin: this.form.isAutoLogin,
            loginType: 'phoneLogin',
            code: data.code,
            expire: data.expire,
            svr_time: info.server_time,
            uid: info.user_id,
            user_name: info.Nickname,
            head_image: info.Portrait,
            isLogin: true
          })
        })
      }).catch(err => {
        if (err && err.code === 12001) {
          this.$refs.form.phoneError = '验证码错误'
        }
        this.loading = false
      })
    },
    /**
     * 切换页面类型
     * @param {String} type 详见 src/views/login/index.vue comType
     */
    changeDialogType (type) {
      this.$xz('xz_substat_action', 1734)
      this.$store.dispatch('user/login', {
        type,
        query: {
          loginType: 'pwd'
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/theme/common/var";
.min-head {
  position: absolute;
  top: 14px;
  left: 16px;
}
.body-wrap {
  width: 270px;
  padding-bottom: 10px;
}
.head {
  margin: 0 0 20px;
  font-size: 18px;
  font-weight: 400;
  text-align: center;
  color: #fff;
}
.login-btn {
  width: 100%;
}
.checkbox-wrap {
  line-height: 1;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  // min-height: 43px;
  /deep/.el-checkbox {
    margin-right: 0;
  }
  .checkbox-btn {
    a {
      color: $--color-primary;
      display: inline-block;
    }
    &:hover {
      a {
        text-decoration: underline;
      }
    }
  }
}
// .el-dialog {
//   /deep/.el-dialog__body {
//     padding-top: 0;
//   }
// }
</style>
